package com.example.carconsumer.controller.dl.admin;

import com.alibaba.dubbo.config.annotation.Reference;
import com.example.carinterface.service.dl.admin.OrderService;
import com.example.carinterface.utils.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/admin/order")
@Api(tags = "admin - 订单管理")
public class OrderController {

    @Reference(check = false)
    private OrderService orderService;

    @PostMapping("/findAll")
    @ApiOperation("订单查询")
    public ResultJson<List<Map<String, Object>>> findAll(@ApiParam(name = "map",
            value = "搜索条件（传入参数）：\n" +
                    "id:订单id，（用于查看具体订单详情）\n" +
                    "condition:模糊查询条件（用户名或手机号或车牌号）\n" +
                    "orderClass:订单类型 1，估损预约修理 2直接预约修理 3代办验车 4年检标 5新车上牌,\n" +
                    "orderSource：订单来源 1后台  2用户，\n" +
                    "state：订单状态 1，待确认 2，待派工 3已派工 4司机已接单 5司机已到达 6 去往修车点 7到达修理厂 8去往检车厂 9到达检测场 10 维修中 11\n" +
                    "  维修完成 12 还车中 13 已完成 14已取消（已退款），\n" +
                    "startTime:下单开始时间，\n" +
                    "endTime:下单结束时间，\n" +

                    "\n返回值结果：\n" +
                    "id：订单编号，\n" +
                    "orderClass:订单；类型 1，估损预约修理 2直接预约修理 3代办验车 4年检标 5新车上牌,\n" +
                    "ownerName:被保险人姓名，\n" +
                    "name:联系人，\n" +
                    "orderSource：订单来源 1后台  2用户，\n" +
                    "tel：联系手机号，\n" +
                    "license_Plate_Number：车牌号，\n" +
                    "drivername：司机名称，\n" +
                    "pickCar：是否接车：1是，-1否，\n" +
                    "state：订单状态 1，待确认 2，待派工 3已派工 4司机已接单 5司机已到达 6 去往修车点 7到达修理厂 8去往检车厂 9到达检测场 10 维修中 11\n\n" +
                    "  维修完成 12 还车中 13 已完成 14已取消（已退款），\n" +
                    "creatTime：下单时间，\n" +
                    "orderState：1已支付，2未支付,\n" +
                    "userSendmassage:给用户发送短信次数啊，\n" +
                    "driverSendmassage:给司机发送短信次数,\n" +
                    "car_Engine_Number:发动机信号，\n" +
                    "pickTime:接车时间，\n" +
                    "pickAdress：接车地址,\n" +
                    "pickCoordinate：接车坐标，\n" +
                    "returnAdress:换车地址，\n" +
                    "returnCoordinate:还车坐标，\n" +
                    "remarks:客户备注，\n" +
                    "orderNo:支付单号，\n" +
                    "payMethod:支付方式，1微信，2支付宝，\n" +
                    "orderState:支付状态，1已支付，2未支付，\n" +
                    "allMoney:订单总金额，\n" +
                    "payMoney:在线支付金额，\n" +
                    "pointPay:积分付款，\n" +
                    "couponPrice:优惠券付款，\n" +
                    "payableMoney:客户应付金额\n" +
                    "estimatedTime:预计结束时间，\n" +
                    "firstDashboardImg：接车仪表盘照片，\n" +
                    "firstCarImg：接车车辆外观，\n" +
                    "lastDashboardImg：还车仪表盘照片\n" +
                    "lastCarImg：还车车辆外观\n" +
                    "licenseImg：行驶证照片" +
                    "") @RequestBody(required = false) Map<String, Object> map) {


        return orderService.findAllOrder(map);
    }

    //修改订单（后台部分）
    @ApiOperation("修改订单详情")
    @PostMapping("/updateOrderOfDriver")
    public ResultJson<String> updateOrderOfDriver(@ApiParam("" +
            "id:订单id，\n" +
            "driver_id:司机id（易理赔订单使用），\n" +
            "") @RequestBody Map<String, Object> map) {

        return orderService.updateOrderOfDriver(map);
    }



    //添加订单
    @ApiOperation("添加订单")
    @PostMapping("/addOrder")
    public ResultJson<String> addOrder(@ApiParam("" +
            "orderClass:订单类型 1，估损预约修理 2直接预约修理 3代办验车 4年检标 5新车上牌,\n" +
            "user_id：用户id，\n" +
            "ownerCard_id: 车主卡id，\n" +
            "ownerName:车主名（车主卡中获取）\n" +
            "license_Plate_Number：车牌号（车主卡中获取）" +
            "telPhone:联系电话,\n" +
            "repairShop_id:店铺id,\n" +
            "driver_id:司机id，\n" +
            "pickTime：接车时间，\n" +
            "pickAdress:接车地址，\n" +
            "pickCoordinate:接车坐标,\n" +
            "returnAdress:还车地址，\n" +
            "returnCoordinate:还车坐标,\n" +
            "remarks：备注，\n" +
            "coupon_id:优惠券id（查询当前用户获取）" +

            "") @RequestBody Map<String, Object> map) {


        return orderService.addOrder(map);

    }

    @ApiOperation("查询所有用户")
    @GetMapping("/findAllUser")
    public ResultJson<List<Map<String, Object>>> findAllUser() {
        return orderService.findAllUser();
    }

    @ApiOperation("根据用户id查询车主卡")
    @GetMapping("/findAllOwnerCardByUserId/{id}")
    public ResultJson<List<Map<String, Object>>> findAllOwnerCardByUserId(@PathVariable Integer id) {
        return orderService.findAllOwnerCardByUserId(id);
    }

    @ApiOperation("查询所有司机")
    @GetMapping("/findAllDriver")
    public ResultJson<List<Map<String, Object>>> findAllDriver() {
        return orderService.findAllDriver();
    }

    @ApiOperation("查询用户所拥有的优惠券")
    @GetMapping("/findCouponByUserId/{id}")
    public ResultJson<List<Map<String, Object>>> findCouponByUserId(@PathVariable Integer id) {
        return orderService.findCouponByUserId(id);
    }


    @ApiOperation("导入订单")
    @RequestMapping(value = "/excelImport", method = RequestMethod.POST)
    public ResultJson<String> uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        ResultJson<String> resultJson = new ResultJson<>();

        String contentType = file.getContentType();

        String fileName = file.getOriginalFilename();

        if (file.isEmpty()) {
            resultJson.setSuccess("文件是空！");

        } else {


            try {

//根据路径获取这个操作excel的实例

                HSSFWorkbook wb = new HSSFWorkbook(file.getInputStream());            //根据页面index 获取sheet页

                HSSFSheet sheet = wb.getSheetAt(0);

//实体类集合

                List<Map<String, Object>> importDatas = new ArrayList<>();

                HSSFRow row = null;

//循环sesheet页中数据从第3行开始，第一行是标题，第二行是字段名称

                System.out.println("列数：==》"+sheet.getPhysicalNumberOfRows());
                for (int i = 2; i < sheet.getPhysicalNumberOfRows(); i++) {
        //获取每一行数据
                    row = sheet.getRow(i);
                    System.out.println("row==>"+row);

                    Map<String, Object> data = new HashMap<>();
                    for (int j = 0; j < 15; j++) {
                        System.out.println("cell==>"+row.getCell(j));
                        row.getCell(j).setCellType(CellType.STRING);
                    }

                    data.put("orderClass", row.getCell(0).getStringCellValue());
                    data.put("user_id", row.getCell(1).getStringCellValue());
                    data.put("ownerCard_id", row.getCell(2).getStringCellValue());
                    data.put("ownerName", row.getCell(3).getStringCellValue());
                    data.put("license_Plate_Number", row.getCell(4).getStringCellValue());
                    data.put("telPhone", row.getCell(5).getStringCellValue());
                    data.put("repairShop_id", row.getCell(6).getStringCellValue());
                    data.put("driver_id", row.getCell(7).getStringCellValue());
                    data.put("pickTime", row.getCell(8).getStringCellValue());
                    data.put("pickAdress", row.getCell(9).getStringCellValue());
                    data.put("pickCoordinate", row.getCell(10).getStringCellValue());
                    data.put("returnAdress", row.getCell(11).getStringCellValue());
                    data.put("returnCoordinate", row.getCell(12).getStringCellValue());
                    data.put("remarks", row.getCell(13).getStringCellValue());
                    data.put("coupon_id", row.getCell(14).getStringCellValue());


                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                    importDatas.add(data);

                }

//循环展示导入的数据，实际应用中应该校验并存入数据库

                System.out.println("data==>"+importDatas);


                for (Map<String, Object> importData : importDatas) {
                    resultJson = orderService.addOrder(importData);
                }
            } catch (Exception e) {

                e.printStackTrace();

            }

        }

        return resultJson;

    }

}
